// stores/user.js
import { defineStore } from 'pinia';

export const useUserStore = defineStore('user', {
  state: () => ({
    uid: '',       // 用户ID
    cookie: '',    // 登录令牌
    _initialized: false // 标记是否已初始化
  }),

  getters: {
    isLoggedIn: (state) => !!state.cookie
  },

  actions: {
    // 初始化store（从localStorage恢复数据）
    initialize() {
      if (this._initialized) return;

      const user = localStorage.getItem('user');
      const cookie = localStorage.getItem('cookie');

      if (user) this.uid = user;
      if (cookie) this.cookie = cookie;

      this._initialized = true;
    },

    // 登录成功后保存数据
    login(uid, cookie) {
      this.uid = uid;
      this.cookie = cookie;

      // 持久化到localStorage
      localStorage.setItem('user', uid);
      localStorage.setItem('cookie', cookie);
    },

    // 退出登录
    logout() {
      this.uid = '';
      this.cookie = '';

      // 清除localStorage
      localStorage.removeItem('user');
      localStorage.removeItem('cookie');
    },

    // 获取当前用户UID（安全访问）
    getUID() {
      return this.uid;
    },

    // 获取当前cookie（安全访问）
    getCookie() {
      return this.cookie;
    }
  }
});